<template>
  <div>
    <!-- 搜索表单 -->
    <div style="margin-bottom: 20px">
      <span style="margin-right: 5px">用户名/邮箱：</span>
      <i-input v-model="searchQuery" placeholder="输入用户名或邮箱" style="width: 200px; margin-right: 10px" />
      <i-button type="primary" icon="ios-search" @click="handleSearch">搜索</i-button>
      <i-button type="default" icon="ios-refresh" @click="resetSearch" style="margin-left: 10px">重置</i-button>
    </div>

    <!-- 用户列表 -->
    <i-table :columns="columns" :data="paginatedUsers" border>
      <template #userName="{ row }">
        {{ row.userName }}
      </template>
      <template #userEmail="{ row }">
        {{ row.userEmail }}
      </template>
      <template #userStatus="{ row }">
        <Switch v-model="userStatusMap[row.userId]" @on-change="() => changeStatus(row)" size="large">
          <template #open>启用</template>
          <template #close>禁止</template>
        </Switch>
      </template>
      <template #actions="{ row }">
        <i-button @click="removeUser(row)" type="error" size="small">删除</i-button>
      </template>
    </i-table>

    <div class="pagination-container">
      <page
        :total="totalUsers"
        :current="currentPage"
        :page-size="pageSize"
        show-elevator
        show-total
        show-sizer
        @on-change="handlePageChange"
        :page-size-opts="[5, 10, 20]"
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { getAllUser, updateUserStatus, deleteUser as deleteUserApi } from '@/api/user';
import { Message } from 'view-ui-plus';

export default {
  setup() {
    const searchQuery = ref('');
    const users = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const userStatusMap = ref({});
    const isSearchTriggered = ref(false); // 新增变量，用于标记是否触发搜索
    const token = getCookieToken() || '';

    const columns = [
      { title: '用户名', key: 'userName', slot: 'userName' },
      { title: '邮箱', key: 'userEmail', slot: 'userEmail' },
      { title: '状态', key: 'userStatus', slot: 'userStatus', align: 'center' },
      { title: '操作', slot: 'actions', align: 'center' },
    ];

    function getCookieToken() {
      const name = 'token=';
      const decodedCookie = decodeURIComponent(document.cookie);
      const ca = decodedCookie.split(';');
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i].trim();
        if (c.indexOf(name) === 0) {
          return c.substring(name.length, c.length);
        }
      }
      return '';
    }

    const fetchUsers = async () => {
      try {
        const response = await getAllUser(token);
        users.value = response.data;

        users.value.forEach(user => {
          userStatusMap.value[user.userId] = user.userStatus === '0';
        });
      } catch (error) {
        Message.error('获取用户列表失败: ' + error.message);
      }
    };

    const filteredUsers = computed(() => {
      if (isSearchTriggered.value && searchQuery.value) { // 仅在点击“搜索”后触发筛选
        return users.value.filter(user =>
          user.userName.includes(searchQuery.value) ||
          user.userEmail.includes(searchQuery.value)
        );
      }
      return users.value;
    });

    const paginatedUsers = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredUsers.value.slice(start, end);
    });

    const totalUsers = computed(() => filteredUsers.value.length);

    const handlePageChange = (page) => {
      currentPage.value = page;
    };

    const handleSearch = () => {
      if (searchQuery.value) {
        isSearchTriggered.value = true; // 仅在点击搜索按钮时更新筛选状态
        currentPage.value = 1;
      } else {
        Message.info('请输入要搜索的用户名或邮箱');
      }
    };

    const resetSearch = () => {
      searchQuery.value = '';
      isSearchTriggered.value = false; // 重置筛选状态
      currentPage.value = 1;
      fetchUsers();
    };

    const changeStatus = async (user) => {
      const newStatus = userStatusMap.value[user.userId] ? '0' : '1';
      try {
        await updateUserStatus(user.userName, newStatus, token);
        user.userStatus = newStatus;
        Message.success('用户状态已更新');
        fetchUsers();
      } catch (error) {
        Message.error('更新用户状态失败: ' + error.message);
      }
    };

    const removeUser = async (user) => {
      try {
        await deleteUserApi(user.userId, token);
        Message.success('用户已删除');
        fetchUsers();
      } catch (error) {
        Message.error('删除用户失败: ' + error.message);
      }
    };

    onMounted(fetchUsers);

    return {
      searchQuery,
      users,
      paginatedUsers,
      columns,
      changeStatus,
      removeUser,
      userStatusMap,
      handleSearch,
      resetSearch,
      currentPage,
      pageSize,
      totalUsers,
      handlePageChange,
    };
  },
};
</script>


<style>
.pagination-container {
  position: fixed;
  bottom: 40px; /* 距离底部的距离 */
  right: 48px; /* 距离右边的距离 */
}
</style>